﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using KOPLibrary;
using System.IO;
using System.Windows.Forms;
using KOPLibrary.AutoComplete;
using KOPLibrary.Forms;
using KOPLibrary.TemplateManagement;
using KOPLibrary.UpdateService;
using System.Diagnostics;
using KOPLibrary.PreferenceManagement;
using KOPLibrary.Exceptions;
using System.Drawing;
using Microsoft.Office.Interop.Word;
using System.Text.RegularExpressions;
using System.Net.Mail;
using KOPLibrary.MailManagement;
using System.Net.Mime;
using KOPLibrary.BarcodeManagement;
using KOP.Forms;
using KOPLibrary.SharePointManagement;


namespace KOP
{
    public partial class KOPRibbonWord : OfficeRibbon
    {
        public KOPRibbonWord()
        {
            InitializeComponent();
        }

        private void KOPRibbon_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void ctlAutoComplete_Click(object sender, RibbonControlEventArgs e)
        {
            WordManager wm = new WordManager(Globals.AutoComplateAddIn.Application);
            List<ContentControl> ctrls = wm.GetContentControlsFromDoc(Globals.AutoComplateAddIn.Application.ActiveDocument, false);
            if (ctrls.Count < 1)
            {
                MessageBox.Show("Şablon doldurualacak alan içermiyor", "Uyarı");
                return;
            }
            Microsoft.Office.Interop.Word.Template template = ((Microsoft.Office.Interop.Word.Template)Globals.AutoComplateAddIn.Application.ActiveDocument.get_AttachedTemplate());
            if (template == null)
            {
                MessageBox.Show("Doldurmak için bir şablon dosyası açınız", "Uyarı");
                return;
            }
            string path = string.Empty;
            string repositorypath = PreferenceManager.ReadKey("DefaultTemplatePath", KOPLibrary.TemplateManagement.TemplateType.Word);
            if (!string.IsNullOrEmpty(repositorypath))
            {
                path = template.FullName.Replace(repositorypath, string.Empty).TrimStart('\\');
                if (Path.IsPathRooted(path)) path = Path.GetFileName(path);
            }

            AutoCompleteManageForm form = new AutoCompleteManageForm(AutoComplateManager.GetData(path), ctrls);
            form.ShowDialog();
        }

        private void gallery1_ItemsLoading(object sender, RibbonControlEventArgs e)
        {
            if (gallery1.Items.Count == 0)
            {
                TemplateManager manager = new TemplateManager(KOPLibrary.TemplateManagement.TemplateType.Word, "");
                manager.RefreshGalleryItems(gallery1);
            }
        }

        private void gallery1_ButtonClick(object sender, RibbonControlEventArgs e)
        {
            if (e.Control.Id == "ctlShowAllTemplates")
            {
                TemplateBrowserForm form = TemplateBrowserForm.Create(KOPLibrary.TemplateManagement.TemplateType.Word, "");
                string selectedTemplate = form.Execute();
                if (!string.IsNullOrEmpty(selectedTemplate))
                {
                    OpenTemplate(selectedTemplate);
                }
            }
            else if (e.Control.Id == "ctlUpdateTemplates")
            {
                Util.UpdateTemplates(KOPLibrary.TemplateManagement.TemplateType.Word);
            }

            else if (e.Control.Id == "ctlTemplateLibraryPreference")
            {
                PreferenceForm form = new PreferenceForm(KOPLibrary.TemplateManagement.TemplateType.Word);
                ((TabControl)form.Controls["ctlTabControl"]).SelectedIndex = 0;
                form.ShowDialog();
            }
        }

        private void OpenTemplate(string template)
        {
            TemplateManager tmanager = new TemplateManager(KOPLibrary.TemplateManagement.TemplateType.Word, "");
            tmanager.AddToRecentlyUsedList(template);
            tmanager.RefreshGalleryItems(gallery1);
            WordManager manager = new WordManager(Globals.AutoComplateAddIn.Application);
            manager.CreateWordDocument(gallery1.SelectedItem.Tag.ToString());
        }

        private void gallery1_Click(object sender, RibbonControlEventArgs e)
        {
            if (gallery1.SelectedItem != null)
            {
                OpenTemplate(gallery1.SelectedItem.Tag.ToString());
            }
        }

        private void ctlAboutButton_Click(object sender, RibbonControlEventArgs e)
        {
            About form = new About();
            form.ShowDialog();

        }

        private void ctlPreferenceButton_Click(object sender, RibbonControlEventArgs e)
        {
            PreferenceForm form = new PreferenceForm(KOPLibrary.TemplateManagement.TemplateType.Word);
            form.ShowDialog();
        }

        private void ctlVersionControl_Click(object sender, RibbonControlEventArgs e)
        {
            Util.UpdateAddin();
        }

        private void ctlSupport_Click(object sender, RibbonControlEventArgs e)
        {
            Util.GoToSupport();
        }

        private void ctlCreateBarcode_Click(object sender, RibbonControlEventArgs e)
        {
            List<string> list = GetBarcodeValues(Globals.AutoComplateAddIn.Application.Selection.Text.Trim());
            if (list.Count < 1)
            {
                MessageBox.Show("Seçili barkod içeriği bulunamadı\nOluşturmak istediğiniz barkod içeriğini döküman üzerinde seçiniz", "Uyarı");
                return;
            }
            BarcodeSettingsForm bcf = new BarcodeSettingsForm();
            if (bcf.Execute())
            {
                List<KeyValuePair<string, Image>> image = BarcodeManager.GetBarcodes(bcf.Settings, list);
                Document doc = Globals.AutoComplateAddIn.Application.Documents.Add(Visible: (object)true);
                BarcodeManager.ShowBarcodesInDocument(image, doc);
            }
        }

        private List<string> GetBarcodeValues(string p)
        {
            if (p.Contains("\a")) p = p.Replace("\a", string.Empty);
            List<string> list = new List<string>();
            string[] barcode = p.Split(new char[] { '\r' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string item in barcode)
            {
                list.Add(item);
            }
            return list;
        }

        private void ctlTemplateDesignerButton_Click(object sender, RibbonControlEventArgs e)
        {
            TemplateDesigner templatedesigner = new TemplateDesigner(Globals.AutoComplateAddIn.Application, KOPLibrary.TemplateManagement.TemplateType.Word);
            templatedesigner.ShowDialog();
            Document doc = templatedesigner.ResultDocument;
            if (doc != null) doc.Activate();
        }

        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            Util.OpenDocumentation();
        }



        private void ctlSecureDocumentBtn_Click(object sender, RibbonControlEventArgs e)
        {
            if ((string)ctlSecureDocumentBtn.SelectedItem.Tag == "ctlSecureDocument")
            {
                string pwd = ProtectDocument.ExecuteProtectDocument(KOPLibrary.TemplateManagement.TemplateType.Word);
                if (!string.IsNullOrEmpty(pwd))
                {
                    Globals.AutoComplateAddIn.Application.ActiveDocument.Password = pwd;
                    if (Util.Confirm("Dokümanı kaydetmek istiyor musunuz ?"))
                        Globals.AutoComplateAddIn.Application.ActiveDocument.Save();
                }
            }
            else if ((string)ctlSecureDocumentBtn.SelectedItem.Tag == "ctlRemovePersonalInfo")
            {
                Globals.AutoComplateAddIn.Application.DisplayDocumentInformationPanel = true;
                if (MessageBox.Show("Doküman başlık ve kişisel bilgiler temizlemek istiyor musunuz ?", "Onayla", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
                {
                    Globals.AutoComplateAddIn.Application.ActiveDocument.RemoveDocumentInformation(Microsoft.Office.Interop.Word.WdRemoveDocInfoType.wdRDIAll);
                    MessageBox.Show("Doküman başlık ve kişisel bilgiler temizlendi. Dokümanı kaydettikten sonra güvenle başkalarıyla paylaşabilirsiniz.");
                }
            }
        }

        private void ctlSecureDocumentBtn_ButtonClick(object sender, RibbonControlEventArgs e)
        {
            if (e.Control.Id == "ctlOpenSecuredDocument")
            {
                OpenProtectedDocument.OpenProtectDocumentResult res = OpenProtectedDocument.ExecuteOpenProtectDocument(KOPLibrary.TemplateManagement.TemplateType.Word);
                if (res != null)
                {
                    WordManager mng = new WordManager(Globals.AutoComplateAddIn.Application);
                    mng.OpenWordDocument(res.DocumentPath, res.DocPwd);
                }
            }
        }

        private void button2_Click(object sender, RibbonControlEventArgs e)
        {

        }

        private void ctlQucikOps_Click(object sender, RibbonControlEventArgs e)
        {
            if ((string)ctlQucikOps.SelectedItem.Tag == "ctlSaveToSp")
                Globals.AutoComplateAddIn.Application.Dialogs[WdWordDialog.wdDialogFileSaveAs].Show();
            else if ((string)ctlQucikOps.SelectedItem.Tag == "ctlSpWfs")
            {
                string docurl = Globals.AutoComplateAddIn.Application.ActiveDocument.FullName;
                SharePointManager spm = new SharePointManager();
                TaskDataList tdl = spm.GetTaskData(docurl, null);
                if (tdl != null)
                {
                    if (tdl.Count > 0)
                    {
                        SPTasksForm sptf = new SPTasksForm(tdl);
                        sptf.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("Geçerli döküman için iş akışı bulunamadı", "Uyarı");
                        return;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(spm.ProcessException))
                    {
                        MessageBox.Show(spm.ProcessException, "Uyarı");
                        return;
                    }
                }
            }
            else if ((string)ctlQucikOps.SelectedItem.Tag == "ctlAddContentControl")
            {
                string text = Globals.AutoComplateAddIn.Application.Selection.Range.Text == null ? "" : Globals.AutoComplateAddIn.Application.Selection.Range.Text;
                if (InputQuery.Execute("Lütfen başlık giriniz", ref text))
                {
                    ContentControl control = Globals.AutoComplateAddIn.Application.Selection.Range.ContentControls.Add(WdContentControlType.wdContentControlRichText);
                    control.Title = text;
                    control.Tag = text;
                    control.Range.Text = text;
                }
            }
            else if ((string)ctlQucikOps.SelectedItem.Tag == "ctlGetFromExcel")
            {
                if (ofExcel.ShowDialog() == DialogResult.OK)
                {
                    ExcelManager mng = new ExcelManager();
                    try
                    {
                        List<string> fields = mng.RetrieveColumns(ofExcel.FileName);
                        foreach (string field in fields)
                        {
                            ContentControl control = Globals.AutoComplateAddIn.Application.Selection.Range.ContentControls.Add(WdContentControlType.wdContentControlRichText);
                            control.Title = field;
                            control.Tag = field;
                            control.Range.Text = field;
                            Globals.AutoComplateAddIn.Application.Selection.EndKey(Unit: 6);
                            Globals.AutoComplateAddIn.Application.Selection.MoveRight(Unit: 1);
                            Globals.AutoComplateAddIn.Application.Selection.TypeParagraph();
                                
                        }
                    }
                    finally
                    {
                        mng.Close();
                    }
                }

            }


        }


        private void ctlEMail_Click(object sender, RibbonControlEventArgs e)
        {
            SendSmartEMailForm form = new SendSmartEMailForm();
            form.Execute(Globals.AutoComplateAddIn.Application.ActiveDocument);
        }

        private void button2_Click_1(object sender, RibbonControlEventArgs e)
        {


        }
    }
}
